import SwiftUI
import UniformTypeIdentifiers
import Foundation
import WallpaperLibrary

@available(macOS 12.0, *)
struct WallpaperManagementView: View {
    enum ResourceType: String, CaseIterable, Identifiable {
        case all = "全部"
        case images = "图片"
        case videos = "视频"
        
        var id: String { self.rawValue }
    }
    @State private var dragOver = false
    @State private var showError = false
    @State private var errorMessage = ""
    @State private var resources: [URL] = []
    @State private var selectedResource: URL?
    @State private var isLoading = false
    @State private var hoveredResource: URL? = nil
    @State private var selectedResourceType: ResourceType = .all
    @State private var currentPage = 1
    private let itemsPerPage = 20
    @State private var bingWallpapers: [URL] = []
    @State private var isLoadingBing = false
    @State private var showBingError = false
    @State private var bingErrorMessage = ""
    @State private var peapixWallpapers: [PeapixWallpaper] = []
    @State private var isLoadingPeapix = false
    @State private var showPeapixError = false
    @State private var peapixErrorMessage = ""
    
    private func fetchPeapixWallpapers() {
        isLoadingPeapix = true
        peapixErrorMessage = ""
        
        guard let url = URL(string: "https://www.peapix.com/bing/feed") else {
            peapixErrorMessage = "无效的API地址"
            showPeapixError = true
            isLoadingPeapix = false
            return
        }
        
        let task = URLSession.shared.dataTask(with: url) { data, response, error in
            DispatchQueue.main.async {
                isLoadingPeapix = false
                
                if let error = error {
                    peapixErrorMessage = "网络请求失败: \(error.localizedDescription)"
                    showPeapixError = true
                    return
                }
                
                guard let data = data else {
                    peapixErrorMessage = "未收到有效数据"
                    showPeapixError = true
                    return
                }
                
                do {
                    let decoder = JSONDecoder()
                    let wallpapers = try decoder.decode([PeapixWallpaper].self, from: data)
                    peapixWallpapers = wallpapers
                } catch {
                    peapixErrorMessage = "解析数据失败: \(error.localizedDescription)"
                    showPeapixError = true
                }
            }
        }
        
        task.resume()
    }

    let onSelectResource: (URL) -> Void
    
    private var headerView: some View {
        VStack(spacing: 8) {
            HStack {
                Text("壁纸管理")
                    .font(.headline)
                Spacer()
                Button(action: {
                    onSelectResource(selectedResource ?? URL(fileURLWithPath: ""))
                }) {
                    Image(systemName: "xmark.circle.fill")
                        .foregroundColor(.gray)
                }
                .buttonStyle(.plain)
            }
            
            Picker("资源类型", selection: $selectedResourceType) {
                ForEach(ResourceType.allCases) { type in
                    Text(type.rawValue).tag(type)
                }
            }
            
            HStack {
                Button("获取Bing壁纸") {
                    fetchBingWallpapers()
                }
                .disabled(isLoadingBing)
                
                Button("获取Peapix壁纸") {
                    fetchPeapixWallpapers()
                }
                .disabled(isLoadingPeapix)
            }
            .pickerStyle(SegmentedPickerStyle())
            .onChange(of: selectedResourceType) { _ in
                loadResources()
            }
        }
        .padding()
        .frame(maxWidth: .infinity)
        .background(Color(.windowBackgroundColor))
    }
    
    private func resourceItemView(_ resource: URL) -> some View {
        ZStack {
            WallpaperPreview(wallpaper: PeapixWallpaper(
                title: resource.lastPathComponent,
                copyright: "",
                date: "",
                pageUrl: "",
                fullUrl: resource,
                thumbUrl: resource,
                imageUrl: resource
            ), isVideo: (try? resource.resourceValues(forKeys: [.contentTypeKey]).contentType)?.conforms(to: .movie) == true,
            )
            
            VStack {
                Spacer()
                HStack {
                    Spacer()
                    if hoveredResource == resource {
                        Button(action: {
                            onSelectResource(resource)
                        }) {
                            Image(systemName: "checkmark.circle.fill")
                                .foregroundColor(.accentColor)
                                .font(.system(size: 24))
                                .padding(8)
                                .background(Color(.windowBackgroundColor).opacity(0.8))
                                .clipShape(Circle())
                        }
                        .buttonStyle(.plain)
                        .padding(8)
                    }
                }
            }
        }
        .onHover { isHovered in
            if isHovered {
                selectedResource = resource
                hoveredResource = resource
            } else if hoveredResource == resource {
                hoveredResource = nil
            }
        }
        .contextMenu {
            Button("删除", role: .destructive) {
                Task {
                    do {
                        try await WallpaperLibrary.shared.removeResource(resource)
                        if selectedResource == resource {
                            selectedResource = nil
                        }
                    } catch {
                        errorMessage = "删除文件失败: \(error.localizedDescription)"
                        showError = true
                    }
                }
            }
        }
    }
    
    private var resourcesGridView: some View {
        ScrollView {
            if !bingWallpapers.isEmpty {
                Section(header: Text("Bing每日壁纸").font(.headline).padding(.top)) {
                    LazyVGrid(columns: [GridItem(.adaptive(minimum: 180), spacing: 16)], spacing: 16) {
                        ForEach(bingWallpapers, id: \.self) { url in
                            WallpaperPreview(wallpaper: PeapixWallpaper(
                                title: "Bing壁纸",
                                copyright: "",
                                date: "",
                                pageUrl: "",
                                fullUrl: url,
                                thumbUrl: url,
                                imageUrl: url
                            ), isVideo: false)
                            .onTapGesture {
                                onSelectResource(url)
                            }
                        }
                    }
                }
            }
            
            if !peapixWallpapers.isEmpty {
                Section(header: Text("Peapix壁纸").font(.headline).padding(.top)) {
                    LazyVGrid(columns: [GridItem(.adaptive(minimum: 180), spacing: 16)], spacing: 16) {
                        ForEach(peapixWallpapers, id: \.fullUrl) { wallpaper in
                            WallpaperPreview(wallpaper: wallpaper, isVideo: false)
                            .onTapGesture {
                                onSelectResource(wallpaper.fullUrl)
                            }
                        }
                    }
                }
            }
            
            LazyVGrid(columns: [GridItem(.adaptive(minimum: 180), spacing: 16)], spacing: 16) {
                ForEach(paginatedResources, id: \.self) { resource in
                    resourceItemView(resource)
                }
            }
            
            HStack {
                Button(action: {
                    if currentPage > 1 {
                        currentPage -= 1
                    }
                }) {
                    Image(systemName: "chevron.left")
                }
                .disabled(currentPage == 1)
                
                Text("第 \(currentPage) 页")
                
                Button(action: {
                    if currentPage < totalPages {
                        currentPage += 1
                    }
                }) {
                    Image(systemName: "chevron.right")
                }
                .disabled(currentPage == totalPages)
            }
            .padding(.vertical, 8)
            .padding(12)
        }
        .background(Color(.textBackgroundColor))
    }
    
    var body: some View {
        VStack(spacing: 0) {
            headerView
            resourcesGridView
        }
            .background(Color(.textBackgroundColor))
            .onDrop(of: [.fileURL], isTargeted: $dragOver) { providers in
                Task {
                    for provider in providers {
                        if let item = try? await provider.loadItem(forTypeIdentifier: UTType.fileURL.identifier),
                           let data = item as? Data,
                           let url = URL(dataRepresentation: data, relativeTo: nil) {
                            do {
                                try await WallpaperLibrary.shared.addResource(url)
                                loadResources()
                            } catch {
                                errorMessage = "添加文件失败: \(error.localizedDescription)"
                                showError = true
                            }
                        }
                    }
                }
                return true
            }
            .alert("错误", isPresented: $showError) {
                Button("确定", role: .cancel) {}
            } message: {
                Text(errorMessage)
            }
            .alert("Bing壁纸错误", isPresented: $showBingError) {
                Button("确定", role: .cancel) {}
            } message: {
                Text(bingErrorMessage)
            }
            .onAppear {
                loadResources()
            }
    }
    
    private var paginatedResources: [URL] {
        let startIndex = (currentPage - 1) * itemsPerPage
        let endIndex = min(startIndex + itemsPerPage, resources.count)
        return Array(resources[startIndex..<endIndex])
    }
    
    private var totalPages: Int {
        Int(ceil(Double(resources.count) / Double(itemsPerPage)))
    }
    
    private func loadResources() {
        switch selectedResourceType {
        case .all:
            resources = WallpaperLibrary.shared.getAllResources()
        case .images:
            resources = WallpaperLibrary.shared.getImageResources()
        case .videos:
            resources = WallpaperLibrary.shared.getVideoResources()
        }
    }
    
    private func fetchBingWallpapers() {
        isLoadingBing = true
        let url = URL(string: "https://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=8&mkt=zh-CN")!
        
        URLSession.shared.dataTask(with: url) { data, response, error in
            DispatchQueue.main.async {
                self.isLoadingBing = false
                
                if let error = error {
                    self.bingErrorMessage = "网络请求失败: \(error.localizedDescription)"
                    self.showBingError = true
                    return
                }
                
                guard let data = data else {
                    self.bingErrorMessage = "没有获取到数据"
                    self.showBingError = true
                    return
                }
                
                do {
                    if let json = try JSONSerialization.jsonObject(with: data) as? [String: Any],
                       let images = json["images"] as? [[String: String]] {
                        let urls = images.compactMap { image in
                            URL(string: "https://www.bing.com" + (image["url"] ?? ""))
                        }
                        self.bingWallpapers = urls
                    }
                } catch {
                    self.bingErrorMessage = "解析JSON失败: \(error.localizedDescription)"
                    self.showBingError = true
                }
            }
        }.resume()
        currentPage = 1
    }
}
